package com.wwj.admin.system.controller;

import com.wwj.core.system.entity.Role;
import com.wwj.core.system.entity.User;
import com.wwj.core.system.service.IRoleService;
import com.wwj.core.system.service.IUserService;
import com.wwj.framework.controller.BaseController;
import com.wwj.framework.utils.Page2EasyUiData;
import com.wwj.framework.utils.ReturnData;
import com.github.pagehelper.Page;
import com.wwj.shiro.ShiroUser;
import com.wwj.utils.encrypt.EncryptUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xya on 16-10-25.
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {

    public static final String INDEX = "/admin/system/user";

    public static final String CREATE = "/admin/system/user_add";

    public static final String EDIT = "/admin/system/user_edit";


    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;

    @RequestMapping(value = {"", "/"})
    public String index() {
        return INDEX;
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create() {
        try {
            List<Role> roles = roleService.findAllRole();
//            List<Shop> shops = shopService.find4Select();
            Map<String,Object> map= new HashMap<String, Object>();
            map.put("roles",roles);
//            map.put("shops",shops);
            return new ModelAndView(CREATE, map);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ModelAndView(ERROR);
        }
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView edit(String id) {
        try {
            User user = userService.findUserById(id);
            List<Role> roles = roleService.findAllRole();
//            List<Shop> shops = shopService.find4Select();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("user", user);
            map.put("roles", roles);
//            map.put("shops",shops);
            return new ModelAndView(EDIT, map);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ModelAndView(ERROR);
        }

    }

    /**
     * 员工列表
     *
     * @param offset 偏移量
     * @param limit  查询记录长度
     * @return ReturnData对象
     */
    @RequestMapping(value = "/listData.json")
    @ResponseBody
    public ReturnData list(@RequestParam(value = "offset", required = false, defaultValue = "0") int offset, @RequestParam(value = "limit", required = false, defaultValue = "10") int limit, Integer shopId, String search, HttpServletRequest request) {
        try {
            int pageNo = offset / limit + 1;
            int pageSize = limit;
            if (null != search && "".equals(search.trim()))
                search = null;
            Page page = userService.findUserByPage(pageNo, pageSize, search);
            ReturnData data = new ReturnData().success(Page2EasyUiData.format(page));
            return data;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ReturnData().failure(e.getMessage());
        }
    }

    /**
     * 新增员工
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public ReturnData create(User user) {
        try {
            userService.createUser(user);
            return new ReturnData().success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ReturnData().failure(e.getMessage());
        }
    }

    /**
     * 新增员工
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public ReturnData edit(User user) {
        try {
            userService.updateUser(user);
            return new ReturnData().success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ReturnData().failure(e.getMessage());
        }
    }

    /**
     * 删除商品
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public ReturnData remove(String id) {
        try {
            userService.deleteUser(id);
            return new ReturnData().success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ReturnData().failure(e.getMessage());
        }
    }

//    @RequestMapping("/validate")
//    @ResponseBody
//    public ReturnData validateEmployeeNo(String employeeNo) {
//        try {
//            boolean flag = userService.validateEmployeeNo(employeeNo);
//            return new ReturnData().success(!flag);
//        } catch (Exception e) {
//            logger.error(e.getMessage(), e);
//            return new ReturnData().failure(e.getMessage());
//        }
//    }


    @RequestMapping(value = "/pwd/setPwd", method = RequestMethod.POST)
    @ResponseBody
    public ReturnData setPwd(String oldPwd, String newPwd, String confirmPwd) throws Exception {
        //获取当前登录人
        ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if (shiroUser == null || shiroUser.getId().equals("")) {
            return null;
        }
        User user = userService.findUserById(shiroUser.getId());
        String pwd = user.getPassword();
        if (oldPwd == null
                || "".equals(oldPwd)
                || !pwd.equals(EncryptUtil.getInstance().MD5(oldPwd))) {
            return new ReturnData().failure("旧密码为空或不正确，请重新输入");
        }

        if (null == newPwd
                || null == confirmPwd
                || !newPwd.equals(confirmPwd)) {
            return new ReturnData().failure("新密码为空或两次输入不一直，请重新输入");
        }
        user.setPassword(EncryptUtil.getInstance().MD5(confirmPwd));
        userService.updatePwd(user);
        return new ReturnData().success("修改成功");
    }
}
